package org.thirdeye.reader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import org.thirdeye.reader.constants.ApplicationConstants;
import org.thirdeye.reader.constants.GestureConstants;
import org.thirdeye.reader.helper.GestureFilter;
import org.thirdeye.reader.helper.GestureFilter.GestureListener;
import org.thirdeye.reader.helper.Reader;

public class ThirdEye_TextReader extends Activity implements GestureListener {

	private SharedPreferences appSettings;

	private char granularity = ApplicationConstants.WORDS;
	private ThirdEye_TextReaderDTO data = new ThirdEye_TextReaderDTO();
	private TextToSpeech tts;
	Reader readerObj = new Reader(data, tts);
	private int appMode = 0;
	private TextView tv;
	private String details;
	private String fileName = "";
	private String encoding = "UTF-16LE";
	private String selectedFont = "latha.ttf";
	private Locale selectedLocale = new Locale("ta");
	private String language = "Tamil";
	private Boolean isAccessibilityEnabled;
	private GestureFilter detector;

	private File currentDir;
	private List<String> dirPath;
	private List<String> dirType;
	private List<String> dirNames;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		appMode = ApplicationConstants.APP_STARTED_MODE;
		tts = new TextToSpeech(this, onInitListener);
		setContentView(R.layout.main);
		detector = new GestureFilter(this, this);
		appSettings = getSharedPreferences(
				ApplicationConstants.SHARED_PREF_NAME, MODE_PRIVATE);
		// Reading from preference if any
		isAccessibilityEnabled = appSettings.getBoolean(
				ApplicationConstants.IS_ACCESSIBILITY_KEY, true);
		Log.d("isAccessibilityEnabled", "" + isAccessibilityEnabled);
		tv = (TextView) findViewById(R.id.TextView01);
		tv.setBackgroundResource(R.drawable.library_books);
		tv.setTextColor(Color.WHITE);
		tv.clearFocus();
		tv.setClickable(false);
		if (!isAccessibilityEnabled) {
			tv.setMovementMethod(new ScrollingMovementMethod());
		}
		tv.setOnKeyListener(new View.OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				Log.d("onKey", "KeyEvent" + event.getKeyCode());
				if (event.getAction() == KeyEvent.ACTION_DOWN
						&& (KeyEvent.KEYCODE_DPAD_DOWN == event.getKeyCode()
								|| KeyEvent.KEYCODE_DPAD_CENTER == event
										.getKeyCode() || KeyEvent.KEYCODE_ENTER == event
								.getKeyCode())) {
					return onKeyDown(keyCode, event);
				}
				return false;
			}
		});

		// Reading from preference if any
		String preferedLang = appSettings.getString(
				ApplicationConstants.LANG_KEY, null);
		if (preferedLang != null) {
			language = preferedLang;
		}
		String preferedFont = appSettings.getString(
				ApplicationConstants.FONT_KEY, null);
		if (preferedFont != null) {
			selectedFont = preferedFont;
		}
		String preferedEncoding = appSettings.getString(
				ApplicationConstants.ENCODE_KEY, null);
		if (preferedEncoding != null) {
			encoding = preferedEncoding;
		}
		Locale loc = getLocaleFromLanguage(language);
		if (tts.isLanguageAvailable(loc) != -1) {
			selectedLocale = loc;
			tts.setLanguage(loc);
			Toast.makeText(getApplicationContext(),
					"Default Language " + language, Toast.LENGTH_SHORT).show();
			tts.speak("Default Language is set to " + language, 0, null);
		} else {
			showMessageBox("Default Language " + language + " is not available");
		}
		try {
			Uri data = getIntent().getData();
			if (data != null) {
				fileName = data.getPath();
				loadFileContents();
			}
		} catch (Exception ioe) {
			Toast.makeText(getApplicationContext(), "File Name:" + fileName,
					Toast.LENGTH_SHORT).show();
			Log.e("", fileName);
			ioe.printStackTrace();
		}
	}

	private void chooseFile(File f) throws Exception {
		File[] dirs = f.listFiles();
		dirPath = new ArrayList<String>();
		dirType = new ArrayList<String>();
		dirNames = new ArrayList<String>();
		List<String> fileNames = new ArrayList<String>();
		List<String> filePath = new ArrayList<String>();
		List<String> fileType = new ArrayList<String>();

		try {
			if (dirs != null) {
				for (File ff : dirs) {
					if (ff.isDirectory()) {
						dirNames.add(ff.getName());
						dirPath.add(ff.getAbsolutePath());
						dirType.add("Folder");
					} else {
						fileNames.add(ff.getName());
						filePath.add(ff.getAbsolutePath());
						fileType.add("File");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}

		dirNames.addAll(fileNames);
		dirPath.addAll(filePath);
		dirType.addAll(fileType);

		if (!f.getName().equalsIgnoreCase("sdcard")) {
			dirNames.add(0, ApplicationConstants.PREV_DIR_NAME);
			dirPath.add(0, f.getParent());
			dirType.add(0, "Parent Directory");
		}
		CharSequence[] items = dirNames.toArray(new CharSequence[dirNames
				.size()]);

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Current Dir: " + f.getName());
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				Log.d("Entering", "onClick() with " + dirType.get(item));
				if (!dirType.get(item).equalsIgnoreCase("file")) {
					try {
						chooseFile(new File(dirPath.get(item)));
					} catch (Exception e) {
						Log.e("Exception", e.getMessage());
					}
				} else {
					onFileClick(item);
				}
			}
		});
		builder.create().show();
	}

	private void onFileClick(int item) {
		String fileName = dirNames.get(item);
		if (fileName.length() > 3) {
			if (isFileTypeSupported(getFileTypeExtension(fileName))) {
				this.fileName = dirPath.get(item);
				data.setSentenceCnt(ApplicationConstants.MAX_SENTENCES);
				loadFileContents();
				return;
			}
		}
		showMessageBox("Sorry unsupported file.");
	}

	private String getFileTypeExtension(String fileName) {
		String fileType = fileName.substring(fileName.length() - 3);
		return fileType;
	}

	private boolean isFileTypeSupported(String fileType) {
		return Arrays.asList(ApplicationConstants.SUPPORTED_FILE_TYPES)
				.contains(fileType);
	}

	private void showMessageBox(String string) {
		AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
		builder1.setMessage(string).setCancelable(false)
				.setNeutralButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		builder1.create().show();
	}

	private void setAccessibilityMenuTitle(MenuItem menuItem) {
		String accessibilityMenuTitle = ApplicationConstants.ACCESSIBILITY_ENABLE_STR;
		Log.d("isAccessibilityEnabled", "" + isAccessibilityEnabled);
		if (isAccessibilityEnabled) {
			accessibilityMenuTitle = ApplicationConstants.ACCESSIBILITY_DISABLE_STR;
		}
		menuItem.setTitle(accessibilityMenuTitle);
	}

	private Locale getLocaleFromLanguage(String givenLanguage) {
		int selectedIndex = 0;
		for (int index = 0; index < ApplicationConstants.LANGUAGES.length; index++) {
			if (ApplicationConstants.LANGUAGES[index].equals(givenLanguage)) {
				selectedIndex = index;
				break;
			}
		}
		Log.d("getLocaleFromLanguage", "LOCALE[selectedIndex]:"
				+ ApplicationConstants.LOCALE[selectedIndex]);
		return new Locale((String) ApplicationConstants.LOCALE[selectedIndex]);
	}

	private void loadFileContents() {
		try {
			// TODO: Need to optimize this
			data.setSentences(loadFile().split("\n"));
			int sentenceLength = data.getSentences().length;
			data.setPageCnt(sentenceLength / data.getSentenceCnt());
			if (sentenceLength % data.getSentenceCnt() != 0) {
				data.setPageCnt(data.getPageCnt() + 1);
			}
			String str;
			str = "Total number of Pages=" + data.getPageCnt()
					+ "\nTotal sentences=" + data.getSentences().length;
			details = str;
			tv.setText(str);
			data.setCurPage(0);
			data.setCurSentence(0);
			if (sentenceLength < data.getSentenceCnt())
				data.setSentenceCnt(sentenceLength);
			updateTextView(readerObj.loadSentences());
			appMode = ApplicationConstants.FILE_OPENED_MODE;
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	private void updateTextView(String text) {
		tv.setText(text);
		tv.setBackgroundResource(R.drawable.blank_page);
		tv.setTextColor(Color.BLACK);
		Typeface face = Typeface.createFromAsset(getAssets(),
				ApplicationConstants.FONTS_PATH + selectedFont);
		tv.setTypeface(face);
	}

	private String loadFile() throws IOException {
		String fileContentString = "";

		File file = new File(fileName);
		FileInputStream in = new FileInputStream(file);
		InputStreamReader tmp = new InputStreamReader(in, encoding);

		// if (getFileTypeExtension(fileName) == "txt")
		{
			BufferedReader reader = new BufferedReader(tmp);
			StringBuffer buf = new StringBuffer();
			String str;
			while ((str = reader.readLine()) != null) {
				buf.append(str + "\n");
			}
			fileContentString = buf.toString();
			reader.close();
		}/*
		 * else if (getFileTypeExtension(fileName) == "rtf") { RTFEditorKit
		 * rtfParser = new RTFEditorKit(); Document document =
		 * rtfParser.createDefaultDocument(); rtfParser.read(new
		 * ByteArrayInputStream(in.toString().getBytes()), document, 0);
		 * fileContentString = document.getText(0, document.getLength()); }
		 */
		return fileContentString;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		setAccessibilityMenuTitle(menu.findItem(R.id.accessibility));
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.open:
			openFile();
			break;
		case R.id.language:
			changeLanguage();
			break;
		case R.id.details:
			tts.speak("Current page is" + (data.getCurPage() + 1) + details, 0,
					null);
			break;
		case R.id.encoding:
			changeEncoding();
			break;
		case R.id.help:
			showHelp();
			break;
		case R.id.close:
			closeApplication();
			break;
		case R.id.tts_setting:
			openTTSSetting();
			break;
		case R.id.accessibility:
			changeAccessibilityOption();
			setAccessibilityMenuTitle(item);
			break;
		case R.id.accessibilitysetting:
			openAccessibilitySetting();
			break;
		case R.id.font:
			changeFont();
			break;
		}

		return true;
	}

	private void openTTSSetting() {
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.setComponent(new ComponentName("com.android.settings",
				"com.android.settings.VoiceInputOutputSettings"));
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}

	private void openAccessibilitySetting() {
		Intent intent = new Intent(
				android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}

	private void changeAccessibilityOption() {
		isAccessibilityEnabled = !isAccessibilityEnabled;
		String ttsString = "Accessibility Mode Enabled";
		if (isAccessibilityEnabled) {
			tv.setMovementMethod(null);
		} else {
			tv.setMovementMethod(new ScrollingMovementMethod());
			ttsString = "Accessibility Mode Disabled";
		}
		tts.speak(ttsString, 0, null);
		Editor prefEditor = appSettings.edit();
		prefEditor.putBoolean(ApplicationConstants.IS_ACCESSIBILITY_KEY,
				isAccessibilityEnabled);
		prefEditor.commit();
	}

	private void openFile() {
		try {
			currentDir = new File(ApplicationConstants.ROOT_PATH);
			chooseFile(currentDir);
		} catch (Exception e) {
			Log.e("e", e.getMessage());
		}
	}

	private void showHelp() {
		showMessageBox("Up Or Swipe Up or E - Previous Sentence\n"
				+ "Down or Swipe Down or X - Next sentence\n"
				+ "Right or Swipe from Right or F - Next Page\n"
				+ "Left or Swipe from Left or S - Previous Page\n"
				+ "A - Read all the contents\n"
				+ "C or Swipe Down diagonally towards Right - Read all the pages from currnt page\n"
				+ "Space - Read current Page\n"
				+ "Centre or Enter or D - Pause/Stop\n"
				+ "O or 0 - Open file\n"
				+ "U or Swipe Up diagonally towards Right - Change encoding\nM  or Swipe Down diagonally towards Left - Change Accessibility Mode\n"
				+ "L or Swipe Up diagonally towards Left - Change language\nT - Open TTS Setting\n"
				+ "H - Help\n" + "Z - Open Accessibility Setting\n"
				+ "Q - Quit\n" + "P - File Details\n"
				+ "G - Change granularity"
				+ "\n\nWebsite: thirdeyetvg.com\nemail: thirdeyetvg@gmail.com");
	}

	private void changeEncoding() {
		AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
		builder1.setTitle("Choose encoding");
		builder1.setItems(ApplicationConstants.AVAILABLE_ENCODING,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						encoding = (String) ApplicationConstants.AVAILABLE_ENCODING[item];
						// Storing in Preference
						Editor prefEditor = appSettings.edit();
						prefEditor.putString(ApplicationConstants.ENCODE_KEY,
								encoding);
						prefEditor.commit();

						loadFileContents();
					}
				});
		builder1.create().show();
	}

	private void changeLanguage() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Choose Language");
		builder.setItems(ApplicationConstants.LANGUAGES,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						updateTextView(readerObj.loadSentences());
						;
						Log.d("changeLanguage", "locale:" + selectedLocale);
						Locale loc = getLocaleFromLanguage((String) ApplicationConstants.LANGUAGES[item]);
						if (tts.isLanguageAvailable(loc) != -1) {
							selectedLocale = loc;
							// Storing in Preference
							Editor prefEditor = appSettings.edit();
							prefEditor
									.putString(
											ApplicationConstants.LANG_KEY,
											(String) ApplicationConstants.LANGUAGES[item]);
							prefEditor.commit();
							tts.setLanguage(loc);
							Toast.makeText(
									getApplicationContext(),
									"Language changed to "
											+ ApplicationConstants.LANGUAGES[item],
									Toast.LENGTH_SHORT).show();
							tts.speak("Language changed to "
									+ ApplicationConstants.LANGUAGES[item], 0,
									null);
						} else {
							showMessageBox("Language "
									+ ApplicationConstants.LANGUAGES[item]
									+ " not available");
						}
					}
				});
		builder.create().show();
	}

	private void changeFont() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Choose Language");
		builder.setItems(ApplicationConstants.FONTS_DESCRIPTION,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						selectedFont = ApplicationConstants.FONTS[item];
						updateTextView(readerObj.loadSentences());
						;
						// Storing in Preference
						Editor prefEditor = appSettings.edit();
						prefEditor.putString(ApplicationConstants.FONT_KEY,
								selectedFont);
						prefEditor.commit();
					}
				});
		builder.create().show();
	}

	private void closeApplication() {
		AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
		builder1.setMessage("Are you sure to exit?")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								tts.shutdown();
								finish();
								System.exit(0);
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		builder1.create().show();
	}

	private TextToSpeech.OnInitListener onInitListener = new TextToSpeech.OnInitListener() {

		@Override
		public void onInit(int status) {
			// TODO Auto-generated method stub
			
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		Log.d("Entering:", "onResume()");

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d("onKey", "onKeyDown" + event.getKeyCode());
		if (tts.isLanguageAvailable(selectedLocale) != -1) {
			if (tts.getLanguage() != selectedLocale)
				tts.setLanguage(selectedLocale);
		} else {
			showMessageBox("Language " + language + " is not available");
		}
		switch (keyCode) {

		case KeyEvent.KEYCODE_SPACE:
			updateTextView(readerObj.readCurrentPage());
			return true;
		case KeyEvent.KEYCODE_C:
			updateTextView(readerObj.readFromPage(data.getCurPage()));
			return true;
		case KeyEvent.KEYCODE_A:
			updateTextView(readerObj.readAllPages());
			return true;
		case KeyEvent.KEYCODE_O:
			openFile();
			return true;
		case KeyEvent.KEYCODE_0:
			openFile();
			return true;
		case KeyEvent.KEYCODE_L:
			changeLanguage();
			return true;
		case KeyEvent.KEYCODE_H:
			showHelp();
			return true;
		case KeyEvent.KEYCODE_U:
			changeEncoding();
			return true;
		case KeyEvent.KEYCODE_G:
			changeGranularity();
			return true;
		case KeyEvent.KEYCODE_P:
			tts.speak("Current page is" + (data.getCurPage() + 1) + details, 0,
					null);
			return true;

			// Quit
		case KeyEvent.KEYCODE_Q:
			closeApplication();
			return true;
		case KeyEvent.KEYCODE_BACK:
			closeApplication();
			return true;

			// Stop
		case KeyEvent.KEYCODE_DPAD_CENTER:
			stopTTS();
			return true;
		case KeyEvent.KEYCODE_ENTER:
			stopTTS();
			return true;
		case KeyEvent.KEYCODE_D:
			stopTTS();
			return true;

			// D-Pad
		case KeyEvent.KEYCODE_DPAD_LEFT:
			return moveLeft();
		case KeyEvent.KEYCODE_S:
			return moveLeft();

		case KeyEvent.KEYCODE_DPAD_UP:
			return moveUp();
		case KeyEvent.KEYCODE_E:
			return moveUp();

		case KeyEvent.KEYCODE_DPAD_RIGHT:
			return moveRight();
		case KeyEvent.KEYCODE_F:
			return moveRight();

		case KeyEvent.KEYCODE_DPAD_DOWN:
			return moveDown();
		case KeyEvent.KEYCODE_X:
			return moveDown();

		case KeyEvent.KEYCODE_M:
			changeAccessibilityOption();
			return true;

		case KeyEvent.KEYCODE_Z:
			openAccessibilitySetting();
			return true;

		case KeyEvent.KEYCODE_T:
			openTTSSetting();
			return true;
		}
		return false;
	}

	private void changeGranularity() {
		granularity = (granularity == ApplicationConstants.LETTERS) ? ApplicationConstants.WORDS
				: ApplicationConstants.LETTERS;
		String granularityStr = "words";
		if (granularity == ApplicationConstants.LETTERS) {
			granularityStr = "letters";
		}
		tts.speak("Granularity is changed to " + granularityStr, 0, null);
	}

	private boolean moveLeft() {
		if (appMode == ApplicationConstants.FILE_OPENED_MODE) {
			data.setCurSentence(0);
			if (data.getCurPage() > 0) {
				data.setCurPage(data.getCurPage() - 1);
				updateTextView(readerObj.loadSentences());
				;
				tts.speak(
						"Page " + (data.getCurPage() + 1) + " of "
								+ data.getPageCnt(), 0, null);
			} else {
				data.setCurPage(0);
				tts.speak("Begining of the text reached", 0, null);
				updateTextView(readerObj.loadSentences());
				;
			}
		}
		return true;
	}

	private boolean moveRight() {
		if (appMode == ApplicationConstants.FILE_OPENED_MODE) {
			data.setCurSentence(0);
			if (data.getCurPage() < data.getPageCnt() - 1) {
				data.setCurPage(data.getCurPage() + 1);
				updateTextView(readerObj.loadSentences());
				;
				// if(!tts.isSpeaking())
				tts.speak(
						"Page " + (data.getCurPage() + 1) + " of "
								+ data.getPageCnt(), 0, null);
			} else {
				data.setCurPage(0);
				tts.speak("End of the text reached", 0, null);
				updateTextView(readerObj.loadSentences());
				;
			}
		}
		return true;
	}

	private boolean moveUp() {
		if (appMode == ApplicationConstants.FILE_OPENED_MODE) {
			if (data.getCurSentence() > 0) {
				data.setCurSentence(data.getCurSentence() - 1);
				String currentSentence = formatOnGranularity(data
						.getPageSentences().get(data.getCurSentence()));
				tts.speak(currentSentence, 0, null);
			} else {
				data.setCurSentence(0);
			}
		}
		return true;
	}

	private String formatOnGranularity(String sentence) {
		if (granularity == ApplicationConstants.WORDS) {
			return sentence;
		} else {
			StringBuffer strBuffer = new StringBuffer();
			char space = ' ';
			String spaceStr = "space";
			for (int i = 0; i < sentence.length(); i++) {
				if (sentence.charAt(i) == space) {
					strBuffer.append(spaceStr);
				} else {
					strBuffer.append(sentence.charAt(i));
					strBuffer.append(space);
				}
			}
			return strBuffer.toString();
		}
	}

	private boolean moveDown() {
		if (appMode == ApplicationConstants.FILE_OPENED_MODE) {
			Log.d("Entering", "moveDown");
			try {
				int curSentence = data.getCurSentence();
				if (curSentence < data.getSentenceCnt()
						&& curSentence < data.getPageSentences().size()) {
					String currentSentence = formatOnGranularity(data
							.getPageSentences().get(data.getCurSentence()));
					tts.speak(currentSentence, 0, null);
					data.setCurSentence(curSentence + 1);
				} else {
					data.setCurSentence(0);
					if (data.getCurPage() < data.getPageCnt() - 1) {
						data.setCurPage(data.getCurPage() + 1);
						updateTextView(readerObj.loadSentences());
						;
					} else {
						data.setCurPage(0);
						tts.speak("End of the text reached", 0, null);
						updateTextView(readerObj.loadSentences());
						;
					}
				}
			} catch (Exception e) {
				Log.e("Exception", "In move down()");
			}
		}
		return true;
	}

	private void stopTTS() {
		Log.d("Stopping", "Stopping TTS");
		try {
			tts.stop();
			data.setAction(ApplicationConstants.STOP);
		} catch (Exception e) {
			Log.e("Exception while Stopping", "");
		}
	}

	@Override
	protected void onDestroy() {
		stopTTS();
		tts.shutdown();
		super.onDestroy();
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent me) {
		this.detector.onTouchEvent(me);
		return super.dispatchTouchEvent(me);
	}

	@Override
	public void onSwipe(int direction) {
		String str = "";
		switch (direction) {

		case GestureConstants.SWIPE_RIGHT:
			moveLeft();
			str = "Swipe Right";
			break;
		case GestureConstants.SWIPE_LEFT:
			moveRight();
			str = "Swipe Left";
			break;
		case GestureConstants.SWIPE_DOWN:
			moveDown();
			str = "Swipe Down";
			break;
		case GestureConstants.SWIPE_UP:
			moveUp();
			str = "Swipe Up";
			break;
		case GestureConstants.SWIPE_UP_LEFT:
			changeLanguage();
			str = "Swipe Up Left";
			break;
		case GestureConstants.SWIPE_UP_RIGHT:
			changeEncoding();
			str = "Swipe Up Right";
			break;
		case GestureConstants.SWIPE_DOWN_LEFT:
			changeAccessibilityOption();
			str = "Swipe Down Left";
			break;
		case GestureConstants.SWIPE_DOWN_RIGHT:
			if (appMode == ApplicationConstants.FILE_OPENED_MODE) {
				tts.speak("Starting to read all the pages from current page.",
						0, null);
				while (tts.isSpeaking())
					;
				updateTextView(readerObj.readFromPage(data.getCurPage()));
			}
			str = "Swipe Down Right";
			break;
		}
		Log.d("Swipe", str);
	}

	@Override
	public void onDoubleTap() {
		openFile();
	}
}